package com.roger.homecenterscreen.ui.components

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.delay
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
import java.util.TimeZone

@Composable
fun DateTimeDisplay(
    modifier: Modifier = Modifier,
    calendarData: com.roger.homecenterscreen.data.repository.CalendarInfo? = null
) {
    // 使用中国时区
    val chinaTimeZone = TimeZone.getTimeZone("Asia/Shanghai")
    var currentTime by remember { mutableStateOf(Calendar.getInstance(chinaTimeZone, Locale.CHINA)) }
    
    LaunchedEffect(Unit) {
        while (true) {
            currentTime = Calendar.getInstance(chinaTimeZone, Locale.CHINA)
            delay(1000) // 每秒更新一次
        }
    }
    
    val dateFormat = SimpleDateFormat("yyyy年MM月dd日", Locale.CHINA).apply {
        timeZone = chinaTimeZone
    }
    val timeFormat = SimpleDateFormat("HH:mm:ss", Locale.CHINA).apply {
        timeZone = chinaTimeZone
    }
    val weekFormat = SimpleDateFormat("EEEE", Locale.CHINA).apply {
        timeZone = chinaTimeZone
    }
    
    val dateString = dateFormat.format(currentTime.time)
    val timeString = timeFormat.format(currentTime.time)
    val weekString = weekFormat.format(currentTime.time)
    
    // 农历信息（优先使用API数据）
    val lunarString = calendarData?.lunarDate ?: getLunarDateString(currentTime)
    
    // 黄历信息（优先使用API数据）
    val huangliInfo = calendarData?.huangliInfo ?: getHuangliInfo(currentTime)
    
    Card(
        modifier = modifier,
        colors = CardDefaults.cardColors(
            containerColor = Color.White.copy(alpha = 0.9f)
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Column(
            modifier = Modifier.padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 数字时间
            Text(
                text = timeString,
                fontSize = 80.sp,
                fontWeight = FontWeight.Bold,
                color = Color.Black
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 日期和星期
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = dateString,
                    fontSize = 30.sp,
                    color = Color.Gray
                )
                Text(
                    text = weekString,
                    fontSize = 30.sp,
                    color = Color.Gray
                )
            }
            
            Spacer(modifier = Modifier.height(12.dp))
            
            // 农历
            Text(
                text = "农历：$lunarString",
                fontSize = 27.sp,
                color = Color.DarkGray
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 黄历信息
            Column(
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text(
                        text = "宜：${huangliInfo.suitable}",
                        fontSize = 19.sp,
                        color = Color(0xFF4CAF50)
                    )
                }
                
                Spacer(modifier = Modifier.height(4.dp))
                
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text(
                        text = "忌：${huangliInfo.unsuitable}",
                        fontSize = 19.sp,
                        color = Color(0xFFF44336)
                    )
                }
            }
        }
    }
}

data class HuangliInfo(
    val suitable: String,
    val unsuitable: String
)

private fun getLunarDateString(calendar: Calendar): String {
    // 简化的农历显示，实际应用中可以接入专业的农历API
    // 确保使用中国时区的日期
    val chinaCalendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"))
    chinaCalendar.timeInMillis = calendar.timeInMillis
    
    val dayOfYear = chinaCalendar.get(Calendar.DAY_OF_YEAR)
    val year = chinaCalendar.get(Calendar.YEAR)
    
    val lunarMonths = listOf(
        "正月", "二月", "三月", "四月", "五月", "六月",
        "七月", "八月", "九月", "十月", "十一月", "十二月"
    )
    
    val lunarDays = listOf(
        "初一", "初二", "初三", "初四", "初五", "初六", "初七", "初八", "初九", "初十",
        "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十",
        "廿一", "廿二", "廿三", "廿四", "廿五", "廿六", "廿七", "廿八", "廿九", "三十"
    )
    
    val monthIndex = (dayOfYear / 30) % lunarMonths.size
    val dayIndex = (dayOfYear % 30).coerceAtMost(lunarDays.size - 1)
    
    return "甲辰年${lunarMonths[monthIndex]}${lunarDays[dayIndex]}"
}

private fun getHuangliInfo(calendar: Calendar): HuangliInfo {
    // 这里是简化的黄历信息，实际应用中可以接入专业的黄历API
    // 确保使用中国时区的日期
    val chinaCalendar = Calendar.getInstance(TimeZone.getTimeZone("Asia/Shanghai"))
    chinaCalendar.timeInMillis = calendar.timeInMillis
    
    val dayOfYear = chinaCalendar.get(Calendar.DAY_OF_YEAR)
    
    val suitableOptions = listOf(
        "出行、开业、结婚",
        "祭祀、祈福、入宅",
        "开工、签约、交易",
        "学习、考试、会友",
        "理财、投资、购物",
        "运动、健身、休息"
    )
    
    val unsuitableOptions = listOf(
        "搬家、装修、动土",
        "手术、治疗、开刀",
        "争吵、诉讼、冲突",
        "破财、借贷、赌博",
        "熬夜、暴饮、暴食",
        "重大决策、冒险"
    )
    
    val suitableIndex = dayOfYear % suitableOptions.size
    val unsuitableIndex = (dayOfYear + 3) % unsuitableOptions.size
    
    return HuangliInfo(
        suitable = suitableOptions[suitableIndex],
        unsuitable = unsuitableOptions[unsuitableIndex]
    )
} 